package com.github.easyms.common.util;

import com.github.easyms.common.constant.EasymsServiceStatus;
import com.github.easyms.common.exception.EasymsException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * Vo校验工具
 *
 * @author Leo.Liao
 * @date 2020-04-12 14:05:44
 */
public class ValidatorHelper {

    private static Validator validator;

    static{
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象全部属性
     * @param object
     * @param groups
     * @throws EasymsException
     */
    public static void validateEntity(Object object, Class<?>... groups) throws EasymsException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            throw new EasymsException(EasymsServiceStatus.INVALID_PARAM,constraintViolations.iterator().next().getPropertyPath());
        }
    }

    /**
     * 校验对象单个参数
     * @param object
     * @param propertyName
     * @param groups
     */
    public static void validateProperty(Object object, String propertyName, Class<?>... groups){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validateProperty(object, propertyName, groups);
        if (!constraintViolations.isEmpty()) {
            throw new EasymsException(EasymsServiceStatus.INVALID_PARAM,constraintViolations.iterator().next().getPropertyPath());
        }
    }



}
